package com.suneee.store.service.impl;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suneee.base.util.ContextHelper;
import com.suneee.category.dao.CategoryDao;
import com.suneee.category.entity.Category;
import com.suneee.channel.dao.ChannelDao;
import com.suneee.channel.entity.Channel;
import com.suneee.component.excel.ExcelUtil;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.enterprise.entity.Enterprise;
import com.suneee.resources.ProductError;
import com.suneee.shop.dao.ShopDao;
import com.suneee.shop.entity.Shop;
import com.suneee.spec.dao.SpecDao;
import com.suneee.spec.entity.Spec;
import com.suneee.store.bean.AdjustStock;
import com.suneee.store.bean.ProductDTO;
import com.suneee.store.bean.ViewStockRecordDTO;
import com.suneee.store.bean.ViewVirtualDepotDTO;
import com.suneee.store.dao.ShopStockDao;
import com.suneee.store.dao.SkuDao;
import com.suneee.store.dao.SpuDao;
import com.suneee.store.dao.StockDetailDao;
import com.suneee.store.dao.StockRecordDao;
import com.suneee.store.dao.StockTempDao;
import com.suneee.store.dao.ViewNoStockRecordSkuDao;
import com.suneee.store.dao.ViewStockRecordDao;
import com.suneee.store.dao.ViewVirtualDepotDao;
import com.suneee.store.entity.Sku;
import com.suneee.store.entity.Spu;
import com.suneee.store.entity.StockDetail;
import com.suneee.store.entity.StockRecord;
import com.suneee.store.entity.StockTemp;
import com.suneee.store.entity.ViewNoStockRecordSku;
import com.suneee.store.entity.ViewVirtualDepot;
import com.suneee.store.resources.StaticParam;
import com.suneee.store.service.ProductService;
import com.suneee.web.bean.DownloadInfo;

@Service("api-productService")
public class ProductServiceImpl implements ProductService {

	@Autowired
	private SpuDao spuDao;

	@Autowired
	private SkuDao skuDao;

	@Autowired
	private ShopStockDao shopStockDao;

	@Autowired
	private StockRecordDao stockRecordDao;

	@Autowired
	private StockDetailDao stockDetailDao;

	@Autowired
	private ViewStockRecordDao viewStockRecordDao;

	@Autowired
	private ViewVirtualDepotDao viewVirtualDepotDao;

	@Autowired
	private CategoryDao categoryDao;

	@Autowired
	private ViewNoStockRecordSkuDao viewNoStockRecordSkuDao;

	@Autowired
	private StockTempDao stockTempDao;

	@Autowired
	private SpecDao specDao;

	@Autowired
	private ShopDao shopDao;

	@Autowired
	private ChannelDao channelDao;

	@Override
	@Transactional
	public void add(Spu product) {
		Assert.notNull(product, "spu");
		Assert.notNull(product.getCategoryId(), "类目不能为空");
		Assert.notEmpty(product.getSkuList(), "添加的商品中没有商品规格信息");
		// 获取当前登录的企业编码
		product.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		// 新增商品界面 判断是否由SPU 携带出来的商品信息。 有则更新，没有则新增
		if (product.getSpuId() != null) {
			// 以下逻辑是SPU 新增商品
			this.editorSpuSkuInfo(product);
		}
		// 以下逻辑是 新增商品
		else {
			this.inserSpuSkuInfo(product);
		}
	}

	/**
	 * 新增商品分支： 直接新增商品（没有选择UPS）
	 */
	public void inserSpuSkuInfo(Spu product) {
		Integer userId = ContextHelper.getCurrentLoginInfo().getAdminId();
		Timestamp tamp = new Timestamp(System.currentTimeMillis());
		product.setCreateUser(userId);
		product.setUpdateUser(userId);
		product.setCreateTime(tamp);
		product.setUpdateTime(tamp);
		// 商品规格只有在确认入库的时候才会被添加到商品信息中。
		// product.setSpecOneValue(null);
		// product.setSpecTwoValue(null);
		// product.setSpecThreeValue(null);
		// product.setSpecFourValue(null);
		// 数据来源(0内部<中台创建>,1企业<ERP对接>,2商城<商城采购>)
		product.setFromType(0);
		spuDao.insert(product);

		// 获取 新建商品时选择的SKU(规格数据)
		List<Sku> skuList = product.getSkuList();
		Integer skuId = null;
		int primary = 0;
		for (int i = 0; i < skuList.size(); i++) {
			if (null != skuList.get(i)) {
				skuList.get(i).setSpuId(product.getSpuId());
				while (true) {
					primary++;
					boolean flag = this.skuPrimary(product.getSpuId() * 1000
							+ primary);
					if (flag) {
						skuId = product.getSpuId() * 1000 + primary;
						break;
					}
				}
				skuList.get(i).setSkuId(skuId);
				skuList.get(i).setTempStock(skuList.get(i).getStock());
				skuList.get(i).setAssignedStock(0);
				skuList.get(i).setStock(0);
				skuList.get(i).setCreateUser(userId);
				skuList.get(i).setUpdateUser(userId);
				skuList.get(i).setCreateTime(tamp);
				skuList.get(i).setUpdateTime(tamp);
			}
		}
		skuDao.insert(product.getSkuList());
		this.saveStockTemp(skuList, StaticParam.IN_TYPE_NEW);
	}

	/**
	 * 判断即将新增的sku 数据主键是否存在 存在返回false 不存在返回true
	 * 
	 * @param skuId
	 * @return
	 */
	public Boolean skuPrimary(Integer skuId) {
		Sku sku = skuDao.select(skuId);
		if (sku == null) {
			return true;
		}
		return false;
	}

	/**
	 * 选择SPU 新增商品
	 * 
	 * @param product
	 */
	public void editorSpuSkuInfo(Spu product) {
		Integer userId = ContextHelper.getCurrentLoginInfo().getAdminId();
		Timestamp tamp = new Timestamp(System.currentTimeMillis());
		product.setUpdateUser(userId);
		product.setUpdateTime(tamp);
		Spu updateSpu = spuDao.select(product.getSpuId());
		if (null != updateSpu) {
			List<Sku> newList = new ArrayList<Sku>();
			List<Sku> updateList = new ArrayList<Sku>();
			// 判断商品是否有规格信息
			if (product.getSkuList() != null && !product.getSkuList().isEmpty()) {
				Integer skuId = null;
				int primary = 0;
				// 遍历商品规格信息
				for (Sku sku : product.getSkuList()) {
					// skuId 不为空则表示商品已经存在此规格（只需要修改）
					if (sku.getSkuId() == null) {
						while (true) {
							primary++;
							boolean flag = this.skuPrimary(product.getSpuId()
									* 1000 + primary);
							if (flag) {
								skuId = product.getSpuId() * 1000 + primary;
								break;
							}
						}
						sku.setSpuId(product.getSpuId());
						sku.setSkuId(skuId);
						sku.setTempStock(sku.getStock());
						sku.setAssignedStock(0);
						sku.setStock(0);
						sku.setUpdateUser(userId);
						sku.setUpdateTime(tamp);
						newList.add(sku);
					} else {
						sku.setSpuId(product.getSpuId());
						updateList.add(sku);
					}
				}

				if (null != newList && newList.size() > 0) {
					// 批量新增商品规格信息
					skuDao.insert(newList);

					// 保存 商品存信息
					this.saveStockTemp(newList, StaticParam.IN_TYPE_NEW);
				}
				if (null != updateList && updateList.size() > 0) {
					skuDao.update(updateList);
				}
			}
			updateSpu.setTitle(product.getTitle());
			updateSpu.setMarketPrice(product.getMarketPrice());// 市场价
			updateSpu.setEnterpriseSpu(product.getEnterpriseSpu()); // 商家编码
			updateSpu.setPurchasePrice(product.getPurchasePrice());// 采购价
			// 修改商品信息
			spuDao.update(updateSpu);
		}
	}

	/*
	 * public void add(Spu product) { Assert.notNull(product, "spu"); //
	 * Assert.notEmpty(product.getSkuList(), "sku");
	 * product.setEnterpriseCode(ContextHelper
	 * .getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
	 * if(product.getSpuId() != null){ spuDao.update(product);
	 * if(product.getSkuList() != null && !product.getSkuList().isEmpty()){
	 * List<Sku> newList = null; List<Sku> updateList = null; for(Sku sku :
	 * product.getSkuList()){ sku.setSpuId(product.getSpuId());
	 * if(sku.getSkuId() == null){ Sku temp = skuDao.getSameSku(sku); if(temp !=
	 * null) continue; if(newList == null) newList = new ArrayList<>();
	 * newList.add(sku); } else{ if(updateList == null) updateList = new
	 * ArrayList<>(); updateList.add(sku); } } if(newList != null){ Integer
	 * maxSkuId = skuDao.getMaxSkuIdBySpuId(product.getSpuId()); for(int i = 0;i
	 * < newList.size();i++){ Sku sku = newList.get(i); maxSkuId++;
	 * sku.setSpuId(product.getSpuId()); sku.setSkuId(maxSkuId);
	 * sku.setTempStock(sku.getAssignedStock()); sku.setAssignedStock(0);
	 * sku.setStock(0); } skuDao.insert(newList); this.saveStockTemp(newList,
	 * StaticParam.IN_TYPE_NEW); } // if(updateList != null) //
	 * skuDao.update(updateList); } return; }
	 * 
	 * product.setCreateTime(new Timestamp(System.currentTimeMillis()));
	 * spuDao.insert(product); List<Sku> skuList = product.getSkuList();
	 * if(skuList != null && !skuList.isEmpty()){ for(int i = 0;i <
	 * skuList.size();i++){ Sku sku = skuList.get(i);
	 * sku.setSpuId(product.getSpuId()); sku.setSkuId(product.getSpuId() * 1000
	 * + i + 1); sku.setTempStock(sku.getAssignedStock());
	 * sku.setAssignedStock(0); sku.setStock(0); }
	 * skuDao.insert(product.getSkuList()); } //
	 * this.inStockNewRecord(skuList,StaticParam.IN_TYPE_NEW,null);//生成入库单
	 * //生成入库缓存 this.saveStockTemp(skuList, StaticParam.IN_TYPE_NEW); }
	 */

	@Override
	public void saveStockTemp(List<Sku> tempList, String stockType) {
		List<StockTemp> inserts = new ArrayList<>();
		List<StockTemp> updates = new ArrayList<>();
		Integer userId = ContextHelper.getCurrentLoginInfo().getAdminId();
		Timestamp timeTamp = new Timestamp(System.currentTimeMillis());

		for (Sku sku : tempList) {

			StockTemp temp = null;
			temp = stockTempDao.getBySkuId(sku.getSkuId());
			if (temp == null) {
				temp = new StockTemp();
				temp.setSpuId(sku.getSpuId());
				temp.setSkuId(sku.getSkuId());
				temp.setStockType(stockType);
				temp.setIncoming(sku.getTempStock());
				temp.setUserId(userId);
				temp.setCreateTime(timeTamp);
				inserts.add(temp);
			} else {
				if (null == temp.getIncoming()) {
					temp.setIncoming(0);
				}
				if (null == sku.getTempStock()) {
					sku.setTempStock(0);
				}
				temp.setIncoming(temp.getIncoming() + sku.getTempStock());
				updates.add(temp);
			}
		}
		if (!inserts.isEmpty())
			stockTempDao.insert(inserts);
		if (!updates.isEmpty())
			stockTempDao.update(updates);
	}

	/*
	 * public void saveStockTemp(List<Sku> tempList,String stockType) { // TODO
	 * Auto-generated method stub List<StockTemp> inserts = new ArrayList<>();
	 * List<StockTemp> updates = new ArrayList<>(); for(Sku sku : tempList){
	 * StockTemp temp = null; temp = stockTempDao.getBySkuId(sku.getSkuId());
	 * if(temp == null){ temp = new StockTemp(); temp.setSpuId(sku.getSpuId());
	 * temp.setSkuId(sku.getSkuId()); temp.setStockType(stockType);
	 * temp.setIncoming(sku.getTempStock()); inserts.add(temp); } else{
	 * temp.setIncoming(temp.getIncoming() + sku.getTempStock());
	 * updates.add(temp); } } if(!inserts.isEmpty())
	 * stockTempDao.insert(inserts); if(!updates.isEmpty())
	 * stockTempDao.update(updates); }
	 */

	@Override
	@Transactional
	public void saveStcokInRecord(List<StockTemp> list, String stockType,
			String remark) {
		Assert.notEmpty(list, "操作对象");
		List<Sku> skuList = new ArrayList<>();
		List<Integer> ids = new ArrayList<>();
		for (StockTemp temp : list) {
			Sku sku = skuDao.select(temp.getSkuId());
			sku.setStock((sku.getStock() == null ? 0 : sku.getStock())
					+ (temp.getIncoming() == null ? 0 : temp.getIncoming()));
			sku.setTempStock(temp.getIncoming() == null ? 0 : temp
					.getIncoming());
			skuList.add(sku);
			ids.add(temp.getTempId());
		}
		this.vStoreSaveInOpt(skuList, stockType, remark);// 生成入库单
		skuDao.update(skuList);
		stockTempDao.delete(ids);
	}

	/**
	 * 虚拟总仓生成入库单
	 * 
	 * @param skuList
	 * @param inTypeFlag
	 * @param remark
	 */
	private void vStoreSaveInOpt(List<Sku> skuList, String inTypeFlag, String remark) {
		StockRecord record = new StockRecord();
		record.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		record.setOperateStoreId(StaticParam.VIRTUAL_WAREHOUSE); // 操作仓id
		record.setRelevantStoreId(StaticParam.VIRTUAL_WAREHOUSE);// 关联仓id

		record.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		record.setCreateTime(new Timestamp(System.currentTimeMillis()));
		record.setRecordType(StaticParam.V_STOCK_TYPE_IN);
		// record.setRelevantStoreId(relevantStoreId);
		record.setRemark(remark);
		if (inTypeFlag.equals(StaticParam.IN_TYPE_NEW))
			record.setStockType(StaticParam.IN_TYPE_NEW);
		if (inTypeFlag.equals(StaticParam.IN_TYPE_UPDATE))
			record.setStockType(StaticParam.IN_TYPE_UPDATE);
		if (inTypeFlag.equals(StaticParam.IN_TYPE_FALLBACK))
			record.setStockType(StaticParam.IN_TYPE_FALLBACK);

		record.setRecordType(StaticParam.V_STOCK_TYPE_IN);
		record.setRemark(remark);
		record.setCreateTime(new Timestamp(System.currentTimeMillis()));
		record.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		record.setChannelCode(StaticParam.VW_CHANNEL_CODE);
		record.setOperateChannelCode(StaticParam.VW_CHANNEL_CODE);// 虚拟总仓渠道标识
		record.setRelevantChannelCode(StaticParam.VW_CHANNEL_CODE);

		List<StockDetail> tempList = new ArrayList<>();
		for (Sku sku : skuList) {
			StockDetail detail = new StockDetail();
			detail.setSpuId(sku.getSpuId());
			detail.setSkuId(sku.getSkuId());
			detail.setIncoming(sku.getTempStock());
			detail.setPrice(sku.getPrice());
			detail.setStatus(StaticParam.IN_STATUS_DONE);
			tempList.add(detail);
		}
		record.setStockDetailList(tempList);
		this.insertStockRecord(record, StaticParam.IN_FLAG);
	}

	@Override
	public void inStockNewRecord(List<Sku> skuList, String inTypeFlag,
			Integer operateStoreId, String remark) {
		StockRecord record = new StockRecord();
		record.setRecordType(StaticParam.V_STOCK_TYPE_IN);
		record.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		record.setCreateTime(new Timestamp(System.currentTimeMillis()));

		if (operateStoreId != null) {
			record.setOperateStoreId(operateStoreId); // 操作仓id
		}
		record.setRelevantStoreId(StaticParam.VIRTUAL_WAREHOUSE);// 关联仓id
		
		Shop shop = shopDao.get(operateStoreId);
		if(shop != null){
			record.setChannelCode(shop.getChannelCode());
			record.setOperateChannelCode(StaticParam.VW_CHANNEL_CODE);// 虚拟总仓渠道标识
			record.setRelevantChannelCode(shop.getChannelCode());
		}

		record.setRemark(remark);
		if (inTypeFlag.equals(StaticParam.IN_TYPE_NEW))
			record.setStockType(StaticParam.IN_TYPE_NEW);
		if (inTypeFlag.equals(StaticParam.IN_TYPE_UPDATE))
			record.setStockType(StaticParam.IN_TYPE_UPDATE);
		if (inTypeFlag.equals(StaticParam.IN_TYPE_FALLBACK))
			record.setStockType(StaticParam.IN_TYPE_FALLBACK);
		record.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		List<StockDetail> tempList = new ArrayList<>();
		for (Sku sku : skuList) {
			StockDetail detail = new StockDetail();
			detail.setSpuId(sku.getSpuId());
			detail.setSkuId(sku.getSkuId());
			detail.setIncoming(sku.getTempStock());
			detail.setPrice(sku.getPrice());
			detail.setStatus(StaticParam.IN_STATUS_DONE);
			tempList.add(detail);
		}
		record.setStockDetailList(tempList);
		this.insertStockRecord(record, StaticParam.IN_FLAG);
	}

	@Override
	public void adjustStock(List<AdjustStock> stockList) {
		// TODO Auto-generated method stub
		Assert.notNull(stockList, "sku");
		StringBuffer sbf = null;
		List<Sku> skuList = null;
		for (AdjustStock stock : stockList) {
			Sku sku = this.selectSku(stock.getSkuId());
			if (sku == null) {
				if (sbf == null)
					sbf = new StringBuffer();
				sbf.append("没有权限操作sku：").append(stock.getSkuId()).append("；");
			} else {
				if (skuList == null)
					skuList = new ArrayList<>();
				// sku.setAssignedStock(stock.getStock());
				sku.setTempStock(stock.getStock());
				skuList.add(sku);
			}
		}
		if (sbf != null)
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,
					sbf.toString());
		if (skuList != null)
			// 生成入库缓存
			this.saveStockTemp(skuList, StaticParam.IN_TYPE_UPDATE);
		// skuDao.update(skuList);
		// this.inStockNewRecord(skuList,StaticParam.IN_TYPE_UPDATE,null);//生成入库单
	}

	@Override
	public Sku selectSku(Integer skuId) {
		// TODO Auto-generated method stub
		Sku sku = skuDao.select(skuId);
		if (sku != null) {
			Spu spu = spuDao.select(sku.getSpuId());
			if (spu != null) {
				if (spu.getEnterpriseCode().equals(
						ContextHelper.getCurrentLoginInfo().getEnterprise()
								.getEnterpriseCode())) {
					return sku;
				}
			}
		}
		return null;
	}

	@Override
	public Page<Spu> listView(ProductDTO dto) {
		if (dto == null)
			dto = new ProductDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		Page<Spu> spuPage = spuDao.listView(dto);
		if (spuPage != null) {
			List<Spu> spuList = spuPage.getItems();
			if (spuList != null && !spuList.isEmpty()) {
				Map<Integer, List<Sku>> skuMap = new HashMap<>();
				List<Integer> spuIdList = new ArrayList<>();
				for (Spu spu : spuList) {
					spuIdList.add(spu.getSpuId());
				}
				List<Sku> skuList = skuDao.queryForListBySpu(spuIdList);
				this.wrapSkuMap(skuMap, skuList);
				for (Spu spu : spuList) {
					Object[] args = new Object[1];
					args[0] = spu.getSpuId();
					List<StockTemp> stockList = stockTempDao.selectWhere(
							" spu_id = ? ", args);
					if (null != stockList) {
						for (Sku sku : skuList) {
							for (StockTemp temp : stockList) {
								if (null != temp.getSkuId()
										&& temp.getSkuId().equals(
												sku.getSkuId())
										&& null != temp.getSpuId()
										&& temp.getSpuId().equals(
												sku.getSpuId())) {
									if (null != temp.getIncoming()
											&& null != sku.getStock()) {
										sku.setStock(sku.getStock()
												+ temp.getIncoming());
									}
									if (null != temp.getIncoming()
											&& null == sku.getStock()) {
										sku.setStock(temp.getIncoming());
									}
									break;
								}
							}
						}
					}
					spu.setSkuList(skuMap.get(spu.getSpuId()));
					if (spu.getSpecIdOne() != null) {
						Spec spec = specDao.select(spu.getSpecIdOne());
						spu.setSpecOneName(spec == null ? null : spec.getName());
					}
					if (spu.getSpecIdTwo() != null) {
						Spec spec = specDao.select(spu.getSpecIdTwo());
						spu.setSpecTwoName(spec == null ? null : spec.getName());
					}
					if (spu.getSpecIdThree() != null) {
						Spec spec = specDao.select(spu.getSpecIdThree());
						spu.setSpecThreeName(spec == null ? null : spec
								.getName());
					}
					if (spu.getSpecIdFour() != null) {
						Spec spec = specDao.select(spu.getSpecIdFour());
						spu.setSpecFourName(spec == null ? null : spec
								.getName());
					}
				}
			}
		}
		return spuPage;
	}

	private void wrapSkuMap(Map<Integer, List<Sku>> target, List<Sku> source) {
		for (Sku sku : source) {
			if (target.get(sku.getSpuId()) == null) {
				List<Sku> skuList = new ArrayList<>();
				target.put(sku.getSpuId(), skuList);
			}
			target.get(sku.getSpuId()).add(sku);
		}
	}

	/**
	 * 出库
	 */
	@Override
	@Transactional
	public void storeManage(StockRecord record) {
		// TODO Auto-generated method stub
		Assert.notNull(record, "出库对象");
		Assert.notNull(record.getStockType(), "出库类型");
		Assert.notNull(record.getRelevantStoreId(), "关联店铺");
		Assert.notNull(record.getRemark(), "出库说明");
		Assert.notNull(record.getStockDetailList(), "出库sku");
		Assert.notEmpty(record.getStockDetailList(), "出库sku");

		if (record.getStockType().equals(StaticParam.OUT_TYPE_ALLOCATION))
			Assert.notNull(record.getRelevantStoreId(), "关联店铺");

		record.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		record.setOperateStoreId(StaticParam.VIRTUAL_WAREHOUSE);
		record.setCreateTime(new Timestamp(System.currentTimeMillis()));
		record.setRecordType(StaticParam.V_STOCK_TYPE_OUT);
		record.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		// record.setRelevantStore(record.getRelevantStore());
		if (null == record.getShopId()) {
			Shop shop = shopDao.select(record.getRelevantStoreId());
			if (shop != null) {
				record.setRelevantStoreId(shop.getShopId());
				record.setOperateChannelCode(StaticParam.VW_CHANNEL_CODE);// 虚拟总仓渠道标识
				record.setChannelCode(shop.getChannelCode());
				record.setRelevantChannelCode(shop.getChannelCode());
			}
		}else{
			Shop shop = shopDao.select(record.getShopId());
			if (shop != null) {
				record.setRelevantStoreId(shop.getShopId());
				record.setOperateChannelCode(StaticParam.VW_CHANNEL_CODE);// 虚拟总仓渠道标识
				
				record.setChannelCode(shop.getChannelCode());
				record.setRelevantChannelCode(shop.getChannelCode());
			}
		}
		record.setRelevantStoreId(record.getShopId());

		for (StockDetail detail : record.getStockDetailList()) {
			Sku sku = skuDao.select(detail.getSkuId());
			sku.setStock(sku.getStock() - detail.getIncoming());
			sku.setAssignedStock(sku.getAssignedStock() + detail.getIncoming());
			skuDao.update(sku);
			detail.setSpuId(sku.getSpuId());
			if (record.getStockType().equals(StaticParam.OUT_TYPE_ALLOCATION))
				detail.setStatus(StaticParam.SYNC_STATUS_WAITTING);
			else
				detail.setStatus(StaticParam.OUT_STATUS_DONE);
		}
		// 生成总仓出库单记录
		this.insertStockRecord(record, StaticParam.OUT_FLAG);
		// 生成店铺入库单记录
	}

	/**
	 * 插入库存记录(虚拟总仓)
	 * 
	 * @param record
	 * @param flag
	 */
	@Override
	public void insertStockRecord(StockRecord record, String flag) {
		String recordId = null;
		synchronized (this) {
			String frontStr = null;
			if (flag.equals(StaticParam.OUT_FLAG))
				frontStr = StaticParam.OUT_FLAG + getDateStr();
			else
				frontStr = StaticParam.IN_FLAG + getDateStr();
			int total = stockRecordDao.getDateTotal(frontStr);
			recordId = frontStr + getNumStr(total);
			record.setRecordId(recordId);
			stockRecordDao.insert(record);
		}
		for (StockDetail detail : record.getStockDetailList()) {
			detail.setRecordId(recordId);
		}
		stockDetailDao.insert(record.getStockDetailList());
	}

	private String getDateStr() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		return sdf.format(new Date());
	}

	private String getNumStr(int total) {
		if (total + 1 < 10)
			return "000" + String.valueOf(total + 1);
		else if (total + 1 < 100)
			return "00" + String.valueOf(total + 1);
		else if (total + 1 < 1000)
			return "0" + String.valueOf(total + 1);
		else
			return String.valueOf(total);
	}

	@Override
	public Page<Map<String, Object>> stockRecordlistView(ViewStockRecordDTO dto) {
		if (dto == null)
			dto = new ViewStockRecordDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		return viewStockRecordDao.viewStockRecordPage(dto);
	}

	@Override
	public Page<Map<String,Object>> ListVirtualDepot(ViewVirtualDepotDTO dto) {
		if (null == dto) {
			dto = new ViewVirtualDepotDTO();
		}
		String type = ContextHelper.getCurrentLoginInfo().getEnterprise().getType();
		if (Enterprise.CLIENT.equals(type)) {
			dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		}
		Page<Map<String,Object>> viewVirtualDepotPage = viewVirtualDepotDao.viewVirtualDepotPage(dto);
		DecimalFormat decimalFormat=new DecimalFormat("##0.00");
		if(viewVirtualDepotPage != null&&viewVirtualDepotPage.getItems().size()>0){
			for (int i = 0; i < viewVirtualDepotPage.getItems().size(); i++) {
				String categoryNames = getCategoryNames(viewVirtualDepotPage.getItems().get(i).get("categoryCode").toString());
				viewVirtualDepotPage.getItems().get(i).put("categoryName", categoryNames);
				if(viewVirtualDepotPage.getItems().get(i).get("marketPrice")!=null)viewVirtualDepotPage.getItems().get(i).put("marketPrice", decimalFormat.format(Float.parseFloat(viewVirtualDepotPage.getItems().get(i).get("marketPrice").toString())));
				if(viewVirtualDepotPage.getItems().get(i).get("advicePrice")!=null)viewVirtualDepotPage.getItems().get(i).put("advicePrice", decimalFormat.format(Float.parseFloat(viewVirtualDepotPage.getItems().get(i).get("advicePrice").toString())));
				if(viewVirtualDepotPage.getItems().get(i).get("price")!=null)viewVirtualDepotPage.getItems().get(i).put("price", decimalFormat.format(Float.parseFloat(viewVirtualDepotPage.getItems().get(i).get("price").toString())));
				
				
			}
		}
		return viewVirtualDepotPage;
	}

	/**
	 * 根据类目编码获取该类目上级名称
	 * 
	 * @param categoryCode
	 * @return
	 */
	@Override
	public String getCategoryNames(String categoryCode) {
		Category category = categoryDao.select(categoryCode);
		if (null == category) {
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		if (categoryCode.length() == 6) {
			String substring = categoryCode.substring(0,
					categoryCode.length() - 2);
			Category category1 = categoryDao.select(substring);
			String substring2 = categoryCode.substring(0,
					categoryCode.length() - 4);
			Category category2 = categoryDao.select(substring2);
			buffer.append(category2.getName()).append(">");
			buffer.append(category1.getName()).append(">");
			buffer.append(category.getName());
		} else if (categoryCode.length() == 4) {
			String substring = categoryCode.substring(0,
					categoryCode.length() - 2);
			Category category1 = categoryDao.select(substring);
			buffer.append(category1.getName()).append(">");
			buffer.append(category.getName());
		} else {
			buffer.append(category.getName());
		}
		return buffer.toString();
	}

	public static final String EXPORT_XLS = "/templates/virtualDepot.export.xls";

	@Override
	public DownloadInfo exportFile(Integer[] skuIds, String title,
			Integer spuId, Integer skuId, String categoryCode) {
		List<ViewVirtualDepot> list = null;
		if (null == skuIds) {
			ViewVirtualDepotDTO dto = new ViewVirtualDepotDTO();
			dto.setTitle(title);
			dto.setSpuId(spuId);
			dto.setSkuId(skuId);
			dto.setCategoryCode(categoryCode);
			dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
					.getEnterpriseCode());
			list = viewVirtualDepotDao.selectAll(dto);
		} else {
			list = viewVirtualDepotDao.exportFile(skuIds);
		}

		for (int i = 0; i < list.size(); i++) {
			ViewVirtualDepot viewVirtualDepot = list.get(i);
			// 数据来源(0内部,1企业,2商城)
			if (0 == viewVirtualDepot.getFromType()) {
				viewVirtualDepot.setFromTypeName("中台创建");
			} else if (1 == viewVirtualDepot.getFromType()) {
				viewVirtualDepot.setFromTypeName("企业");
			} else {
				viewVirtualDepot.setFromTypeName("商城");
			}
			String categoryNames = getCategoryNames(viewVirtualDepot
					.getCategoryCode());
			viewVirtualDepot.setCategoryName(categoryNames);
			StringBuffer spec = new StringBuffer();
			if (!StringUtils.isBlank(viewVirtualDepot.getSpecOneValue())) {
				spec.append(viewVirtualDepot.getSpecOneValue()).append("/");
			}
			if (!StringUtils.isBlank(viewVirtualDepot.getSpecTwoValue())) {
				spec.append(viewVirtualDepot.getSpecTwoValue()).append("/");
			}
			if (!StringUtils.isBlank(viewVirtualDepot.getSpecThreeValue())) {
				spec.append(viewVirtualDepot.getSpecThreeValue()).append("/");
			}
			if (!StringUtils.isBlank(viewVirtualDepot.getSpecFourValue())) {
				spec.append(viewVirtualDepot.getSpecFourValue());
			} else {
				if (spec.length() > 0) {
					spec.deleteCharAt(spec.length() - 1);
				}
			}
			viewVirtualDepot.setSpecOneValue(spec.toString());
		}
		DownloadInfo downloadInfo = ExcelUtil.writeExcle(EXPORT_XLS, list,
				ExcelUtil.replaceTimestamp("虚拟总仓商品列表"));
		return downloadInfo;
	}

	@Override
	public List<ViewNoStockRecordSku> getNoStockRecordSku() {
		// TODO Auto-generated method stub
		String enterpriseCode = ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode();
		List<ViewNoStockRecordSku> list = viewNoStockRecordSkuDao
				.listView(enterpriseCode);
		for (ViewNoStockRecordSku vSku : list) {
			String categoryNames = getCategoryNames(vSku.getCategoryCode());
			vSku.setCategoryName(categoryNames);
		}
		return list;
	}

	@Override
	public Page<Spu> getSpuPage() {
		// TODO Auto-generated method stub
		ProductDTO dto = new ProductDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		Page<Spu> spuPage = spuDao.listView(dto);
		return spuPage;
	}

	@Override
	public List<Sku> queryForListBySpuId(Integer spuId) {
		// TODO Auto-generated method stub
		return skuDao.queryForListBySpuId(spuId);
	}

	@Override
	public Page<Map<String, Object>> mapView(ProductDTO dto) {
		// TODO Auto-generated method stub
		if (dto == null)
			dto = new ProductDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		return shopStockDao.mapView(dto);
	}

}
